package com.itcast.mallweb.controller;


import com.itcast.admin.dto.RiderDTO;
import com.itcast.admin.entity.Admin;
import com.itcast.admin.entity.Rider;
import com.itcast.mallweb.service.RiderService;
import com.itcast.result.Result;
import com.itcast.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/admin/rider")
@Slf4j
@Api(tags = "web-骑手相关接口")
public class RiderController {
    @Autowired
    private RiderService riderService;
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/add")
    @ApiOperation("新增骑手")
    public Result addRider(RiderDTO rdiderDTO , @RequestParam("image") MultipartFile image) {
        log.info("新增骑手的信息为：{}", rdiderDTO);
        log.info("骑手头像上传,{}", image.getOriginalFilename());
        try {
            //原始文件名
            String originalFilename = image.getOriginalFilename();
            //截取原始文件名的后缀 37-57cj.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//截取最后一个点的后半部分
            //构建新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            //文件的请求路径
            String upload = aliOssUtil.upload(image.getBytes(), objectName);
            rdiderDTO.setAvatar(upload);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        riderService.addRider(rdiderDTO);
        return Result.success();
    }

    @GetMapping("/query")
    @ApiOperation("查询单个骑手")
    public Result<Rider> getById(@RequestParam Long id) {
        log.info("骑手的id为：{}", id);
        Rider rider = riderService.getById(id);
        return Result.success(rider);
    }

    @GetMapping("/queryAll")
    @ApiOperation("查询全部骑手")
    public Result<List<Rider>> getRider() {
        log.info("查询全部骑手");
        List<Rider> riderList = riderService.getRider();
        return Result.success(riderList);
    }

    @PostMapping("/detele")
    @ApiOperation("批量删除骑手")
    public Result deteleRider(@RequestBody List<Long> ids) {
        log.info("批量删除骑手的id为：{}", ids);
        riderService.deteleRider(ids);
        return Result.success();
    }

    @PostMapping("/order")
    @ApiOperation("骑手分配订单")
    public void addAllocation(@RequestBody com.itcast.applet.dto.RiderDTO riderDTO) {
        log.info("骑手分配信息为:{}",riderDTO);
        riderService.addAllocation(riderDTO);
    }


}
